//
//  LoginViewController.m
//  IntegralDog
//
//  Created by HanenDev on 16/1/25.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterVC.h"
#import "TabbarController.h"
#import "Macro.h"
#import "ForgetPassViewController.h"
#import "UserModel.h"

#define SCREENWIDTH self.view.bounds.size.width
#define SCREENHEIGHT self.view.bounds.size.height


@interface LoginViewController ()<UITextFieldDelegate,UIGestureRecognizerDelegate>
{
    UITextField *telTextField;
    UITextField *passwordTextField;
    UIButton    *loginBtn;
}
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = YES;
    
    [self createView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardDidHideNotification object:nil];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;

}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.navigationController.navigationBarHidden = NO;

}
- (void)createView
{
    CGFloat HEIGHT = 40.0f;
    CGFloat WIDTH = SCREENWIDTH - 2*[UIView getWidth:30];
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    imageView.image = [UIImage imageNamed:@"Bg.jpg"];
    [self.view addSubview:imageView];
    
    telTextField = [[UITextField alloc]initWithFrame:CGRectMake([UIView getWidth:30], self.view.centerY+ [UIView getHeight:20] , WIDTH, HEIGHT)];
    telTextField.backgroundColor = [UIColor clearColor];
    telTextField.placeholder = @"输入积分狗账号登录";
    telTextField.borderStyle = UITextBorderStyleNone;
    telTextField.keyboardType = UIKeyboardTypeNumberPad;
    telTextField.delegate = self;
    [self.view addSubview:telTextField];
    
    passwordTextField = [[UITextField alloc]initWithFrame:CGRectMake(telTextField.x, telTextField.maxY+[UIView getHeight:10], WIDTH - 80, HEIGHT)];
    passwordTextField.backgroundColor = [UIColor clearColor];
    passwordTextField.placeholder = @"请输入密码";
    passwordTextField.borderStyle = UITextBorderStyleNone;
    passwordTextField.secureTextEntry = YES;
    passwordTextField.delegate = self;
    [self.view addSubview:passwordTextField];
    
    [telTextField addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    [passwordTextField addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    
    for (int i=0; i<2; i++) {
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(telTextField.x, telTextField.maxY + i*([UIView getHeight:10]+40), WIDTH, 1)];
        lineView.backgroundColor = cellGrayColor;
        [self.view addSubview:lineView];
    }
    
    UIButton *forgetBtn = [[UIButton alloc]initWithFrame:CGRectMake(passwordTextField.maxX , passwordTextField.y, 80, HEIGHT)];
    [forgetBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [forgetBtn setTitleColor:fontLightGrayColor forState:UIControlStateNormal];
    [forgetBtn.titleLabel setFont:[UIFont systemFontOfSize:15.0f]];
    [forgetBtn addTarget:self action:@selector(toSearchMima:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:forgetBtn];
    
//    loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(telTextField.x, passwordTextField.maxY+[UIView getHeight:40], WIDTH , [UIView getHeight:40])];
//    //[loginBtn setTitle:@"登 陆" forState:UIControlStateNormal];
//    //[loginBtn setBackgroundColor:[UIColor orangeColor]];
//    [loginBtn setImage:[UIImage imageNamed:@"Btn_Normal_login"] forState:UIControlStateNormal];
//    [loginBtn setImage:[UIImage imageNamed:@"Btn_Login_Selected"] forState:UIControlStateSelected];
//    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [loginBtn addTarget:self action:@selector(clickToMain:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:loginBtn];
    loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(telTextField.x, passwordTextField.maxY+[UIView getHeight:40], WIDTH , [UIView getHeight:40])];
    [loginBtn setImage:[UIImage imageNamed:@"Btn_Normal_login"] forState:UIControlStateNormal];
    [loginBtn setImage:[UIImage imageNamed:@"Btn_Login_Selected"] forState:UIControlStateSelected];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn.titleLabel setFont:[UIFont systemFontOfSize:20]];
    [loginBtn setBackgroundColor:mainOrangeColor];
    loginBtn.layer.cornerRadius = 4.0;//圆角
    [loginBtn addTarget:self action:@selector(clickToMain:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:loginBtn];
    
    
    UIButton *registerBtn = [[UIButton alloc]initWithFrame:CGRectMake(loginBtn.x, loginBtn.maxY + [UIView getHeight:15], WIDTH, 30)];
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:@"没有账号?我要注册"];
    [string setAttributes:@{NSForegroundColorAttributeName : fontLightGrayColor2 ,NSFontAttributeName : [UIFont systemFontOfSize:15.0f]} range:NSMakeRange(0, 5)];
    [string setAttributes:@{NSForegroundColorAttributeName : fontLightGrayColor ,NSFontAttributeName : [UIFont systemFontOfSize:15.0f]} range:NSMakeRange(5, 4)];
    [registerBtn setAttributedTitle:string forState:UIControlStateNormal];
    [registerBtn addTarget:self  action:@selector(goToRegister:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerBtn];
    
    
}
#pragma mark
#pragma mark textfield 代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    if(textField == passwordTextField){
        [telTextField resignFirstResponder];
        [passwordTextField resignFirstResponder];
        [self clickToMain:loginBtn];
    }
    return YES;
}


- (void)clickToMain:(UIButton *)sender
{

    if (telTextField.text == nil | [telTextField.text length] == 0 ){
        [self.view makeToast:@"请输入手机号"];
        return;
    }else if (![JudgeNumber boolenPhone:telTextField.text]){
        [self.view makeToast:@"请输入正确的手机号"];
        return;
    }else if (passwordTextField.text == nil | [passwordTextField.text length] == 0 ){
        [self.view makeToast:@"请输入密码"];
        return;
    }else if ([passwordTextField.text length] < 6 ){
        [self.view makeToast:@"密码不小于6位"];
        return;
    }
    [telTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
    
    
//    TabbarController *vc = [[TabbarController alloc]init];
//    
//    [self presentViewController:vc animated:YES completion:nil];
    
    [self loginToMain];
    
}
- (void)loginToMain{
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = @{@"telphone":telTextField.text,@"password":passwordTextField.text};
    
    NSLog(@"%@",dic);
    [DataTool postWithUrl:LOGIN_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = IntegrationJsonParserWithData(data);
        int code = [jsonDic[@"code"] intValue];
        if(code != 100)
        {
            NSString * message = jsonDic[@"message"];
            NSLog(@"%@",message);
            [self.view makeToast:message];
            
        }else{
            
            NSString * token = jsonDic[@"token"];
            NSDictionary *user = jsonDic[@"user"];
            
            NSDictionary *dict = [DataTool changeType:user];
            UserModel *model = [[UserModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            
            NSString * userid = (NSString *)[dict objectForKey:@"uid"];
            NSString * telephone = (NSString *)[dict objectForKey:@"telephone"];
            NSString * nickname = (NSString *)[dict objectForKey:@"nickname"];
            NSString * logo = (NSString *)[dict objectForKey:@"logo"];
            int integral = [[dict objectForKey:@"integral"]intValue];
            //NSLog(@"  ggggggggggggggggggg    %@",userid);
            [defaults setObject:token forKey:@"token"];
            [defaults setObject:userid forKey:@"uid"];
            [defaults setObject:telephone forKey:@"telephone"];
            [defaults setObject:nickname forKey:@"nickname"];
            [defaults setObject:logo forKey:@"logo"];
            [defaults setInteger:integral forKey:@"integral"];
            
            [defaults setObject:passwordTextField.text forKey:@"password"];
            
            [defaults synchronize];
            
            TabbarController *vc = [[TabbarController alloc]init];
            UIWindow *window = [UIApplication sharedApplication].delegate.window;
            window.rootViewController = vc;
            
            //[self presentViewController:vc animated:YES completion:nil];
        }
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
        [self.view makeToast:@"登录失败"];
    }];

    
}
- (void)toSearchMima:(UIButton *)sender
{
    NSLog(@"忘记密码");
    //[self presentViewController:[[ForgetPassViewController alloc]init] animated:NO completion:nil];
    [self.navigationController pushViewController:[[ForgetPassViewController alloc]init] animated:NO];
}

- (void)goToRegister:(UIButton *)btn{
    [self.navigationController pushViewController:[[RegisterVC alloc]init] animated:NO];
}

- (void)textFieldChanged:(UITextField *)textField{
    if (textField == telTextField) {
        if ([telTextField.text length] > 20) {
            telTextField.text = [telTextField.text substringToIndex:20];
        }
    }
    if (textField == passwordTextField) {
        if ([passwordTextField.text length] > 20) {
            passwordTextField.text = [passwordTextField.text substringToIndex:20];
        }
    }
    
}

- (void)keyboardWillShow:(NSNotification *)notify{
    
    NSDictionary *dic = notify.userInfo;
    CGRect keyFrame = [dic [UIKeyboardFrameEndUserInfoKey]CGRectValue];
    CGFloat diff = ABS(keyFrame.origin.y - loginBtn.maxY);
    CGFloat time = [dic [UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    if (loginBtn.maxY > keyFrame.origin.y)  {
        [UIView animateWithDuration:time animations:^{
            CGAffineTransform transform = CGAffineTransformMakeTranslation(0, -diff);
            self.view.transform = transform;
        }];
    }
}

- (void)keyboardWillHide:(NSNotification *)notify{
    NSDictionary *dic = notify.userInfo;
    
    CGFloat timer = [dic [UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:timer animations:^{
        CGAffineTransform form = CGAffineTransformIdentity;
        self.view.transform = form;
    }];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
